iT邦幫忙

2022 iThome 鐵人賽

DAY 1
0
Software Development

30而Leet{code}系列 第 1

D1 - [Array] 2 Sum 暖身操

  • 分享至 

  • xImage
  •  

前言

練習 Leetcode 是面試大公司必經的天堂路,即使沒有要面試,定期練習 Leetcode 也可以增加對 Coding 的熟練度,保持最佳手感,這樣平時工作時也可以增加效率.

所謂「三十而立,四十而不惑,五十而知天命」,個人覺得至少要寫30題 Leetcode 以上才算是剛進入門坎.真的要掌握一門語言怎麼說也得做至少 50 題 Medium Level 的才可以.

身爲一個 DevOps 工程師,Python 和 Go 是我平時最常用的兩個語言,所以我決定在今年的挑戰中,逼自己用這兩種語言每天練習一題 LeetCode.

第一天從最簡單 2 Sum 開始吧

問題

https://leetcode.com/problems/two-sum/

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:

2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.

提示

  1. 做 Loop 時,與其每次都比對後面的元素,不如往前比對.
    https://ithelp.ithome.com.tw/upload/images/20220915/20130321BzCWRpdHOM.png

  2. 保存每個元素在陣列中對應的 index 的最佳方式是利用 hash table.

解答

Python

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashmap = {}
        for i in range(len(nums)):
            completeValue = target - nums[i]
            if completeValue in hashmap:
                return (i, hashmap[completeValue])
            hashmap[nums[i]] = i

Go

func twoSum(nums []int, target int) []int {
    
    hashmap := map[int]int{}
    for i := 0; i < len(nums); i++ {
        completeValue := target - nums[i]
        completeValueIndex, completeValueExist := hashmap[completeValue]
        if completeValueExist {
            return  []int{i, completeValueIndex}
        } else {
            hashmap[nums[i]] = i
        }
    }
    return []int{}

}

下一篇
D2 - [Array] 2 Sum II - Input Array Is Sorted
系列文
30而Leet{code}30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言